
package org.rujue.modules.sys.web;

import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.rujue.common.web.ResponseResult;
import org.rujue.modules.sys.utils.SysUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.rujue.common.config.Global;
import org.rujue.common.utils.StringUtils;
import org.rujue.common.web.BaseController;
import org.rujue.modules.sys.entity.Menu;
import org.rujue.modules.sys.service.SystemService;
import org.rujue.modules.sys.utils.UserUtils;

/**
 * 菜单Controller
 * @author ThinkGem
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/menu")
public class MenuController extends BaseController {

	@Autowired
	private SystemService systemService;
	
	@ModelAttribute("menu")
	public Menu get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return systemService.getMenu(id);
		}else{
			return new Menu();
		}
	}
	@RequiresPermissions("sys:menu:view")
	@GetMapping()
	public String menu() {
		return "modules/sys/menu/menuList";
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping("/allMenuData")
	@ResponseBody
	public Map<String, Object> allMenuData() {
		Map<String, Object> map = Maps.newHashMap();
		map.put("code","0");
		List<Menu> list = UserUtils.queryAllList();
		map.put("count",list.size());
		map.put("data",list);
		return map;
	}

	@RequiresPermissions("sys:menu:view")
	@RequestMapping(value = "form")
	public String form(Menu menu, Model model) {
		if (menu.getParent()==null||menu.getParent().getId()==null){
			menu.setParent(new Menu(Menu.getRootId()));
		}
		if(menu.getIsNewRecord()){
			menu.setType(SysUtils.MENU_TYPE_MENU);
		}
		menu.setParent(systemService.getMenu(menu.getParent().getId()));
		// 获取排序号，最末节点排序号+30
		if (StringUtils.isBlank(menu.getId())){
			List<Menu> list = Lists.newArrayList();
			List<Menu> sourcelist = systemService.findAllMenu();
			Menu.sortList(list, sourcelist, menu.getParentId(), false);
			if (!list.isEmpty()){
				menu.setSort(list.get(list.size()-1).getSort() + 30);
			}
		}
		model.addAttribute("menu", menu);
		return "modules/sys/menu/menuForm";
	}
	
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "save")
	public String save(Menu menu, Model model, RedirectAttributes redirectAttributes) {
		if(!UserUtils.getUser().isAdmin()){
			addMessage(redirectAttributes, "越权操作，只有超级管理员才能添加或修改数据！");
			return "redirect:" + adminPath + "/sys/role/?repage";
		}
		if (!beanValidator(model, menu)){
			return form(menu, model);
		}
		systemService.saveMenu(menu);
		addMessage(redirectAttributes, "保存菜单成功");
		return "redirect:" + adminPath + "/sys/menu";
	}
	
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping("/delete")
	@ResponseBody
	public ResponseResult delete(Menu menu) {
		try {
			systemService.deleteMenu(menu);
		} catch (Exception e) {
			// 使用日志框架记录异常信息
			logger.error("菜单删除失败：", e);
			return ResponseResult.error("删除失败: " + e.getMessage());
		}
		return ResponseResult.success("删除成功");
	}


	/**
	 * 批量修改菜单排序
	 */
	@RequiresPermissions("sys:menu:edit")
	@RequestMapping(value = "updateSort")
	public String updateSort(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/menu";
		}
    	for (int i = 0; i < ids.length; i++) {
    		Menu menu = new Menu(ids[i]);
    		menu.setSort(sorts[i]);
    		systemService.updateMenuSort(menu);
    	}
    	addMessage(redirectAttributes, "保存菜单排序成功!");
		return "redirect:" + adminPath + "/sys/menu";
	}
	
	/**
	 * isShowHide是否显示隐藏菜单
	 * @param extId         排除的ID
	 * @param isShowHide   是否显示隐藏菜单，1为显示，0为隐藏
	 * @return 返回菜单树结构JSON数据
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId,@RequestParam(required=false) String isShowHide) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Menu> list = systemService.findAllMenu();
        for (Menu e : list) {
            if (StringUtils.isBlank(extId) || !extId.equals(e.getId()) && !e.getParentIds().contains("," + extId + ",")) {
                if (isShowHide != null && isShowHide.equals("0") && e.getIsShow().equals("0")) {
                    continue;
                }
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
		return mapList;
	}
}
